<?php
/**
 * Enter description here...
 *
 * @package if
 * @subpackage module.db.drivers.pdo
 * @since 1.0.1
 */
class IDbPdoPostgres extends IAbstractDbPdo {
	protected $pdoType = "pgsql";
	
	protected $startQuote = "\"";
	protected $endQuote = "\"";	
	
	protected $metaTableSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%' and schemaname  not in ( 'pg_catalog','information_schema') union select viewname,'V' from pg_views where viewname not like 'pg\_%'  and schemaname  not in ( 'pg_catalog','information_schema')";
	
	protected $default = array(
		"port" => 5432
	);
	
	function nConnect() {
		parent::nConnect("pgsql:host=" . $this->config("host") . " port=" . $this->config("port") . " dbname=" . $this->config("dbname") . " user=" . $this->config("username") . " password=" . $this->config["password"]);
	}
	
	/**
	 * Enter description here...
	 *
	 * @param unknown_type $name
	 * @return array
	 */
	function describeTable($name) {
		$keys = $this->fetchAll($this->nativeExec("SELECT ic.relname AS index_name, a.attname AS column_name,i.indisunique AS unique_key, i.indisprimary AS primary_key FROM pg_class bc, pg_class ic, pg_index i, pg_attribute a WHERE bc.oid = i.indrelid AND ic.oid = i.indexrelid AND (i.indkey[0] = a.attnum OR i.indkey[1] = a.attnum OR i.indkey[2] = a.attnum OR i.indkey[3] = a.attnum OR i.indkey[4] = a.attnum OR i.indkey[5] = a.attnum OR i.indkey[6] = a.attnum OR i.indkey[7] = a.attnum) AND a.attrelid = bc.oid AND bc.relname = '{$name}'"), IDb::FETCH_ASSOC);
		$keys = if_array_combine($keys, "column_name");
		
		$rows = $this->fetchAll($this->nativeExec("SELECT a.attname,t.typname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,a.attnum FROM pg_class c, pg_attribute a,pg_type t WHERE relkind in ('r','v') AND (c.relname='{$name}' or c.relname = lower('{$name}')) and a.attname not like '....%%'
AND a.attnum > 0 AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum"), IDb::FETCH_NUM);
		$fields = array();
		
		foreach ($rows as $row) {
			$fld = new stdClass();
			$fld->name = $row[0];
			$fld->type = $row[1];
			$fld->max_length = $row[2];
			$fld->attnum = $row[6];
			
			if ($fld->max_length <= 0) $fld->max_length = $row[3]-4;
			if ($fld->max_length <= 0) $fld->max_length = -1;
			if ($fld->type == 'numeric') {
				$fld->scale = $fld->max_length & 0xFFFF;
				$fld->max_length >>= 16;
			}
			
			$fld->has_default = ($row[5] == 't');
			if ($fld->has_default) {
				$fld->default_value = $rsdefa[$row[6]];
			}

			$fld->not_null = $row[4] == 't';

			if (isset($keys[$fld->name]) && $keys[$fld->name]['primary_key'] == 't') 
				$fld->primary_key = true;
			if (isset($keys[$fld->name]) && $keys[$fld->name]['unique_key'] == 't') 
				$fld->unique = true; 
			
			$fld->data_type = $this->dataType($fld->type);
			$fields[$fld->name] = get_object_vars($fld);
		}
		return $fields;
	}	
	
	function nLimit($sql, $count, $offset = 0) {
		return $sql . " LIMIT {$count} OFFSET {$offset}";
	}	
}


?>